/***********************************************
 This file is part of redia-bapps-main-ios.
 
 Copyright (c) 2015 Redia A/S
 
 Redia-bapps-main-ios is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.
 
 Redia-bapps-main-ios is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.
 
 You should have received a copy of the GNU General Public License
 along with redia-bapps-main-ios.  If not, see <http://www.gnu.org/licenses/>.
 
 *********************************************** */

//
//  BAPatronSettings.m
//  redia-bapps-ios
//
//  Created by Henrik Lynbech on 14/08/13.
//  Copyright (c) 2013 Redia A/S. All rights reserved.
//

#import "BAPatronSettings.h"
#import "BASettingsUserDefaultsKeys.h"
#import "Keychain.h"
#import "BALibrarySettings.h"

@interface BAPatronSettings () {
    BOOL librarianAccessRole;
    BOOL imfEditorAccessRole;
}

@end

@implementation BAPatronSettings

SINGLETON_IMPL_GCD(BAPatronSettings)

- (void)setPatronObject:(BAPatron *)patronObject
{
    _patronObject = patronObject;
    
    librarianAccessRole=NO;
    imfEditorAccessRole=NO;
    for (NSString* role in _patronObject.roles) {
        if ([role isEqualToString:@"librarianAccess"]) {
            librarianAccessRole=YES;
        } else if ([role isEqualToString:@"imfEditorAccess"]) {
            imfEditorAccessRole=YES;
        }
    }
    
    [[NSNotificationCenter defaultCenter] postNotificationName:BA_PATRON_SETTINGS_OBJECT_CHANGED object:nil];
}

- (NSString *)getLoggedInPatronName
{
    NSString* name = self.patronObject.patronName;
    if (name!=nil) {
        return name;
    }
    return @"";
}

- (NSString *)getLoggedInPatronPreferredBranch
{
    return self.patronObject.patronBranch;
}


#pragma mark - Storing of login credentials

- (BOOL)userSelectedDontShowScannerIntro
{
    return [[NSUserDefaults standardUserDefaults] boolForKey:BASETTINGS_DONT_SHOW_SCANNER_INTRO_KEY];
}

- (void)setUserSelectedDontShowScannerIntro:(BOOL)dontShowIntro
{
    [[NSUserDefaults standardUserDefaults] setBool:dontShowIntro forKey:BASETTINGS_DONT_SHOW_SCANNER_INTRO_KEY];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (NSString*)concatenateWithLibraryID:(NSString*)prefix
{
    NSString* libraryId = [BARPCManager instance].libraryId;
    if ([libraryId length]>0) {
        return [NSString stringWithFormat:@"%@%@",prefix,libraryId];
    } else {
        [NSException raise:@"libraryID invalid in concatenateWithLibraryID" format:@"libraryID unexpectedly empty"];
    }
    return nil;
}

- (BOOL)persistLoginInfo
{
    return [[NSUserDefaults standardUserDefaults] boolForKey:[self concatenateWithLibraryID:BASETTINGS_STORE_LOGIN_INFO_KEY_PREFIX]];
}

- (void)setPersistLoginInfo:(BOOL)persistLoginInfo
{
    [[NSUserDefaults standardUserDefaults] setBool:persistLoginInfo forKey:[self concatenateWithLibraryID:BASETTINGS_STORE_LOGIN_INFO_KEY_PREFIX]];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (NSString*)persistedUserName
{
    /* was:
    return [[NSUserDefaults standardUserDefaults] stringForKey:BASETTINGS_USERNAME_KEY];
     */
    return [Keychain getStringForKey:[self concatenateWithLibraryID:BA_SEC_SETTINGS_USERNAME_KEY_PREFIX]];
}

- (void)setPersistedUserName:(NSString *)userName
{
     /* was:
    [[NSUserDefaults standardUserDefaults] setObject:userName forKey:BASETTINGS_USERNAME_KEY]; //FIXME: SHOULD MOVE TO KEYCHAIN! (because of CPR)
    [[NSUserDefaults standardUserDefaults] synchronize];
      */
    [Keychain saveString:userName forKey:[self concatenateWithLibraryID:BA_SEC_SETTINGS_USERNAME_KEY_PREFIX]];
}

- (NSString*)persistedPassword
{
     /* was:
    return [[NSUserDefaults standardUserDefaults] stringForKey:BASETTINGS_PASSWORD_KEY]; //FIXME: SHOULD MOVE TO KEYCHAIN!
      */
    return [Keychain getStringForKey:[self concatenateWithLibraryID:BA_SEC_SETTINGS_PASSWORD_KEY_PREFIX]];
}

- (void)setPersistedPassword:(NSString *)password
{
     /* was:
    [[NSUserDefaults standardUserDefaults] setObject:password forKey:BASETTINGS_PASSWORD_KEY];
    [[NSUserDefaults standardUserDefaults] synchronize];
      */
    [Keychain saveString:password forKey:[self concatenateWithLibraryID:BA_SEC_SETTINGS_PASSWORD_KEY_PREFIX]];
}

- (void)setPersistedCredentialsForUser:(NSString *)userName password:(NSString *)password
{
     /* was:
    [[NSUserDefaults standardUserDefaults] setObject:userName forKey:BASETTINGS_USERNAME_KEY];
    [[NSUserDefaults standardUserDefaults] setObject:password forKey:BASETTINGS_PASSWORD_KEY];
    [[NSUserDefaults standardUserDefaults] synchronize];
      */
    [self setPersistedUserName:userName];
    [self setPersistedPassword:password];
}

- (void)clearPersistedCredentials
{
     /* was:
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:BASETTINGS_USERNAME_KEY];
    [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:BASETTINGS_PASSWORD_KEY];
    [[NSUserDefaults standardUserDefaults] synchronize];
      */
    [Keychain deleteStringForKey:[self concatenateWithLibraryID:BA_SEC_SETTINGS_USERNAME_KEY_PREFIX]];
    [Keychain deleteStringForKey:[self concatenateWithLibraryID:BA_SEC_SETTINGS_PASSWORD_KEY_PREFIX]];
}


#pragma mark - Acceptance of privacy policy. 
// Note that this information is stored for each user that has been logged in to
// the application.

- (void)addUserToAcceptedUsers:(NSString *)userName
{
    NSDictionary *dict = [[NSUserDefaults standardUserDefaults] dictionaryForKey:BASETTINGS_CPRACCEPT_KEY];
    if ([dict objectForKey:userName] == nil) {
        NSMutableDictionary *newDict = [NSMutableDictionary dictionaryWithDictionary:dict];
        [newDict setObject:@"" forKey:userName];
        [[NSUserDefaults standardUserDefaults] setObject:newDict forKey:BASETTINGS_CPRACCEPT_KEY];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
}

- (BOOL)hasUserAcceptedPolicy:(NSString *)userName
{
    NSDictionary *cprPolicyMap = [[NSUserDefaults standardUserDefaults] dictionaryForKey:BASETTINGS_CPRACCEPT_KEY];
    return [cprPolicyMap objectForKey:userName] != nil;
}

-(BOOL)isUserAllowedLibrarianAccessForCurrentLibrary
{
    return ([[BALibrarySettings instance] isLibrarianModeAllowed] && librarianAccessRole);
}

-(BOOL)isUserAllowedIMFEditorAccessForCurrentLibrary
{
    return ([[BALibrarySettings instance] isImfEnabled] && imfEditorAccessRole);
}

- (void)setLibrarianPreferredMaterialHistoryBranchCode:(NSString*)branchCode
{
    [[NSUserDefaults standardUserDefaults] setObject:branchCode forKey:BA_PATRON_SETTINGS_LIBRARIAN_PREFERRED_BRANCH_KEY];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [[NSNotificationCenter defaultCenter] postNotificationName:BA_PATRON_SETTINGS_LIBRARIAN_PREFERRED_BRANCH_CHANGED object:nil];
}

- (NSString*)getLibrarianPreferredMaterialHistoryBranchCode
{
    NSString* code = [[NSUserDefaults standardUserDefaults] stringForKey:BA_PATRON_SETTINGS_LIBRARIAN_PREFERRED_BRANCH_KEY];
    return code;
}

@end
